package hz.mobileproject.pda.firesafety.activity;

import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.activity.CaptureActivity;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import hz.mobileproject.pda.R;
import hz.mobileproject.pda.broadcast.HandleBroadcast;
import hz.mobileproject.pda.broadcast.IShowBarcodeStr;
import hz.mobileproject.pda.entity.Photo;
import hz.mobileproject.pda.entity.request.Request_loadPoliceInfo;
import hz.mobileproject.pda.entity.response.Response_loadPoliceInfo;
import hz.mobileproject.pda.firesafety.adapter.StartFireAdapter;
import hz.mobileproject.pda.firesafety.bean.Request_queryFireFighting;
import hz.mobileproject.pda.firesafety.bean.Request_start_fire;
import hz.mobileproject.pda.firesafety.bean.Rp_queryfire;
import hz.mobileproject.pda.firesafety.bean.Rp_startFire;
import hz.mobileproject.pda.firesafety.bean.Rq_callingFire;
import hz.mobileproject.pda.firesafety.bean.Rq_endFire;
import hz.mobileproject.pda.firesafety.view.FireSafetyCallingDialog;
import hz.mobileproject.pda.listener.CustomNetCallBack;
import hz.mobileproject.pda.network.Constance;
import hz.mobileproject.pda.ui.base.BaseActivity;
import hz.mobileproject.pda.ui.view.LoadingDialog;
import hz.mobileproject.pda.utils.CommonUtil;
import hz.mobileproject.pda.utils.HttpRqUtils;
import hz.mobileproject.pda.utils.TakePhotoUtil;

/**
 * Created by Lc on 2018/2/28.
 */

@ContentView(R.layout.activity_start_fire_safety)
public class StartFireSatetyActivity extends BaseActivity implements IShowBarcodeStr {
    @ViewInject(R.id.tv_curNum)
    private TextView tv_curNum;
    @ViewInject(R.id.tv_count)
    private TextView tv_count;
    @ViewInject(R.id.lv_fire_safety)
    private ListView lv_fire_safety;
    @ViewInject(R.id.bt_zxing_code_fire)
    private Button bt_zxing_code_fire;

    /**
     * 扫码相关---------------------------
     */
    private HandleBroadcast mHandleBroadcast;
    private SoundPool mSoundpool;
    private LoadingDialog mLoadingDialog;
    private FireSafetyCallingDialog mCallingDialog;
    private static final int SCAN_PLOCE_REQUEST_CODE = 0x111;
    private static final int SCAN_THING_REQUEST_CODE = 0x222;
    //红外扫描音效id
    private int mSoundid;
    //上次扫码时间
    private long mLastScanTime;

    private Gson mGson;
    private StartFireAdapter mAdapter;
    //当前扫码民警
    private Response_loadPoliceInfo mPoliceInfo;
    //开始检查返回信息
    private Rp_startFire mStartFire;
    //当前清点下标
    private int mCallingIndex;
    //当前已点的数量
    private int mAlreadyCallingCount = 0;

    @Override
    protected void initData() {
        if (!Constance.isNeiMeng) {
            bt_zxing_code_fire.setVisibility(View.GONE);
        }
        mGson = new Gson();
        mAdapter = new StartFireAdapter(this, new ArrayList<Rp_queryfire>());
        lv_fire_safety.setAdapter(mAdapter);
        openScan(SCAN_PLOCE_REQUEST_CODE);
    }

    /**
     * 打开扫描
     */
    private void openScan(int requestCode) {
        mLoadingDialog = new LoadingDialog(this);
        if (Constance.isNeiMeng) {  //如果是演示版本则打开相机扫描
            //打开二维码扫描界面
            if (CommonUtil.isCameraCanUse()) {
                Intent intent = new Intent(this, CaptureActivity.class);
                startActivityForResult(intent, requestCode);
            } else {
                Toast.makeText(this, "请打开此应用的摄像头权限！", Toast.LENGTH_SHORT).show();
            }
        } else {
            mHandleBroadcast = new HandleBroadcast(this, this);
            mSoundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
            mSoundid = mSoundpool.load("/etc/Scan_new.ogg", 1);
            mLoadingDialog.setMessage("请扫描民警二维码").show();
        }
    }

    @Event({R.id.bt_fire_end,R.id.bt_zxing_code_fire})
    private void viewOnClick(View v) {
        switch (v.getId()) {
            case R.id.bt_fire_end:
                endFireCalling();
                break;
            case R.id.bt_zxing_code_fire:
                openScan(SCAN_THING_REQUEST_CODE);
                break;
        }
    }

    @Override
    public void updateText(String msg) {
        long nowTime = System.currentTimeMillis();
        if (nowTime - mLastScanTime > 1000) {
            mLastScanTime = nowTime;
        } else {
            //如果时间间隔小于1秒不处理本次扫描
            return;
        }
        if (mLoadingDialog.isShowing()) {
            //弹窗是扫描民警
            //获取民警信息
            getPliceInfoFromSer(msg);
        } else {
            //没弹窗时候扫描的是消防器材
            fireFightingCalling(msg);
        }
    }


    /**
     * 请求网络接口获取民警信息
     *
     * @param scanStr
     */
    private void getPliceInfoFromSer(String scanStr) {
//        if (scanStr.indexOf("P") != 0) {
//            ToastUtils.showLong("条码格式错误，请确认为民警条码");
//            return;
//        }
//        scanStr = scanStr.substring(scanStr.indexOf("P") + 1);
        scanStr = scanStr.contains("P") ? scanStr.substring(1) : scanStr;
        Request_loadPoliceInfo rq_lpi = new Request_loadPoliceInfo();
        rq_lpi.setCusNumber(SPUtils.getInstance("app_login").getString(Constance.SP_CUSNUMBER));
        rq_lpi.setPoliceCode(scanStr);
        //发送获取民警信息接口请求
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_LOAD_POLICE_INFO, rq_lpi, policeInfoCallback);
    }


    /**
     * 获取民警信息接口回调
     */
    private CustomNetCallBack policeInfoCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            mPoliceInfo = mGson.fromJson(data, Response_loadPoliceInfo.class);
            if (mPoliceInfo == null) {
                ToastUtils.showLong("民警信息为空");
                return;
            }
            mLoadingDialog.dismiss();
            startFireFighting();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {

        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("获取民警信息失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 调用开始清点接口
     */
    private void startFireFighting() {
        Request_start_fire rq = new Request_start_fire();
        rq.cus_number = mPoliceInfo.getCus_number() + "";
        rq.dept_id = mPoliceInfo.getPolice_id();
        rq.dept_name = mPoliceInfo.getDepartment_name();
        rq.police_id = mPoliceInfo.getPolice_id();
        rq.police_name = mPoliceInfo.getPolice_name();
        rq.time = TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS));
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_FIREGIGHTING_START, rq, startFireFightingCallBack);
    }

    /**
     * 调用开始清点接口回调
     */
    private CustomNetCallBack startFireFightingCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            mStartFire = mGson.fromJson(data, Rp_startFire.class);
            if (mStartFire == null || mStartFire.getCheck_id() == null) {
                ToastUtils.showLong("开始检查返回数据有误，数据为空");
                return;
            }
            queryFireFighting();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("开始检查失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("开始检查失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 调用加载列表接口
     */
    private void queryFireFighting() {
        Request_queryFireFighting rq = new Request_queryFireFighting();
        rq.cus_number = mPoliceInfo.getCus_number() + "";
        rq.dept_id = mPoliceInfo.getDepartment_id() + "";
        rq.check_id = mStartFire.getCheck_id();
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_FIREGIGHTING_QUERY_LIST, rq, queryFireFightingCallBack);
    }

    /**
     * 调用加载列表接口回调
     */
    private CustomNetCallBack queryFireFightingCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            LogUtils.e(data);
            List<Rp_queryfire> list = mGson.fromJson(data, new TypeToken<ArrayList<Rp_queryfire>>() {
            }.getType());
            mAdapter.clearAdd(list);
            tv_curNum.setText(mAlreadyCallingCount + "");
            tv_count.setText(mAdapter.getCount() + "");
            if (list == null || list.size() == 0) {
                ToastUtils.showLong("数据列表为空");
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("加载列表失败："+rtnMsg);
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("加载列表失败");
            LogUtils.e(ex);
        }
    };

    /**
     * 清点弹窗
     */
    private void fireFightingCalling(String msg) {
        if (mCallingDialog != null && mCallingDialog.isShowing()) {
            ToastUtils.showLong("扫码无效，请先处理本次清点扫码");
            return;
        }
        mCallingIndex = -1;
        for (int i = 0; i < mAdapter.getListData().size(); i++) {
            if (msg.equals(mAdapter.getListData().get(i).getAsset_code())) {
                mCallingIndex = i;
                break;
            }
        }
        if (mCallingIndex >= 0) {
            //如果存在列表中弹出清点框
            final Rp_queryfire tempQueryfire = mAdapter.getListData().get(mCallingIndex);
            mCallingDialog = new FireSafetyCallingDialog(this, tempQueryfire);
            mCallingDialog.setmListener(new FireSafetyCallingDialog.OnSaveClickListner() {
                @Override
                public void onSaveClick(String question, List<Photo> photos) {
                    //调用清点接口
                    Rq_callingFire callingFire = new Rq_callingFire();
                    callingFire.setAsset_code(tempQueryfire.getAsset_code());
                    callingFire.setCheck_id(mStartFire.getCheck_id());
                    callingFire.setCus_number(mPoliceInfo.getCus_number() + "");
                    callingFire.setPolice_id(mPoliceInfo.getPolice_id());
                    callingFire.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
                    callingFire.setCondition(question);

                    if (photos.size() > 0) {
                        //当有图片的时候
                        File[] files = new File[photos.size()];
                        for (int i = 0; i < photos.size(); i++) {
                            Photo tempPhoto = photos.get(i);
                            File f = FileUtils.getFileByPath(tempPhoto.getPath());
                            files[i] = f;
                        }
                        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_FIREGIGHTING_CALLING, callingFire, files, callingCallBack);
                    } else {
                        //没有图片的时候
                        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_FIREGIGHTING_CALLING_NO_PIC, callingFire, callingCallBack);
                    }
                }
            }).show();
        } else {
            //不存在列表中提示
            ToastUtils.showLong("扫码结果不在器材列表中");
        }
    }


    /**
     * 清点回调
     */
    private CustomNetCallBack callingCallBack = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            if (mCallingDialog != null) {
                mCallingDialog.dismiss();
            }
            ToastUtils.showLong("上传成功");
            mAdapter.deleteOne(mCallingIndex);
            mAlreadyCallingCount++;
            tv_curNum.setText(mAlreadyCallingCount + "");
            if (mAdapter.getCount() <= 0) {
                endFireCalling();
            }
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("清点失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("清点失败");
            LogUtils.e(ex);
        }
    };


    /**
     * 结束清点
     */
    private void endFireCalling() {
        Rq_endFire endFire = new Rq_endFire();
        endFire.setCheck_id(mStartFire.getCheck_id());
        endFire.setCus_number(mPoliceInfo.getCus_number() + "");
        endFire.setTime(TimeUtils.getNowString(new SimpleDateFormat(Constance.DATE_YMDHMS)));
        HttpRqUtils.httpPost(Constance.BASE_URL + Constance.URL_FIREGIGHTING_END, endFire, endFireCallback);
    }


    /**
     * 结束清点回调
     */
    private CustomNetCallBack endFireCallback = new CustomNetCallBack() {
        @Override
        public void onSuccessFromSer(int rtnCode, String rtnMsg, String data) {
            ToastUtils.showLong("结束清点成功");
            StartFireSatetyActivity.this.finish();
        }

        @Override
        public void onErrorFromSer(int rtnCode, String rtnMsg) {
            ToastUtils.showLong("结束清点失败");
        }

        @Override
        public void onErrorFromNet(Throwable ex, boolean isOnCallback) {
            ToastUtils.showLong("结束清点失败");
            LogUtils.e(ex);
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            String mImageFilePath = TakePhotoUtil.getInstance(StartFireSatetyActivity.this).getCurPicPath(requestCode, data);
            LogUtils.e("照片路径:" + mImageFilePath);
            if (StringUtils.isEmpty(mImageFilePath)) {
                ToastUtils.showLong("照片路径错误");
                return;
            }
            if (mCallingDialog != null && mCallingDialog.isShowing()) {
                mCallingDialog.getmAdapter().add(new Photo(mImageFilePath));
            }
        }
        if (SCAN_PLOCE_REQUEST_CODE == requestCode && resultCode == CaptureActivity.RESULT_CODE_QR_SCAN) {
            getPliceInfoFromSer(data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN));
        }
        if (SCAN_THING_REQUEST_CODE == requestCode && resultCode == CaptureActivity.RESULT_CODE_QR_SCAN) {
            fireFightingCalling(data.getStringExtra(CaptureActivity.INTENT_EXTRA_KEY_QR_SCAN));
        }
    }

}
